import re
import time

from ascript.android.screen import Ocr
from ascript.android import action
from ascript.android.system import Device
from ascript.android import screen

from .config import CONFIG


class MY_ACTION:
    def __init__(self):
        # 开发屏幕像素
        self.dev_pixels = (1080, 2160)
        # 当前屏幕像素
        self.pixels = self.get_pixels()
        # 当前屏幕像素，基于开发屏幕大小，坐标缩放比例
        self.pixels_per = self.get_pixels_per()

    def get_pixels(self):
        display = Device.display()
        width = display.widthPixels
        height = display.heightPixels
        if CONFIG.my_action_log:
            print(f"[get_pixels] {width}*{height}")
        return (width, height)

    def get_pixels_per(self):
        x_per = round(self.pixels[0] / self.dev_pixels[0], 1)
        y_per = round(self.pixels[1] / self.dev_pixels[1], 1)
        if CONFIG.my_action_log:
            print(f"[get_pixels_per]: ({x_per}, {y_per})")
        return (x_per, y_per)

    def click_text(self, text, type=1, start_x_per=1, start_y_per=1):
        """
        type 1:全匹配  2:正则
        :param text:
        :param type:
        :param start_x_per:
        :param start_y_per:
        :return:
        """
        res = Ocr.mlkitocr_v2()
        if res is None:
            if CONFIG.my_action_log:
                print("[click_text]文字识别失败")
            return False
        else:
            x = 0
            y = 0
            for r in res:
                if CONFIG.my_action_log:
                    print(f"[click_text: {text} match {r.text}]")

                if type == 1 and text != r.text:
                    continue
                if type == 2 and re.search(text, r.text) is None:
                    continue

                temp_x = r.center_x
                temp_y = r.center_y

                flag = True
                if start_x_per != 1 and temp_x < self.pixels[0] * start_x_per:
                    if CONFIG.my_action_log:
                        print(f"[click_text: x < {start_x_per})")
                    flag = False

                if start_y_per != 1 and temp_y < self.pixels[1] * start_y_per:
                    if CONFIG.my_action_log:
                        print(f"[click_text: y < {start_y_per})")
                    flag = False

                if flag:
                    x = temp_x
                    y = temp_y
                    break
                else:
                    continue

            if x == 0 or y == 0:
                return False
            else:
                if CONFIG.my_action_log:
                    print(f"[click_text: {text}]:({x}, {y})")
                action.click(x, y)
                return True

    def click_(self, x, y):
        action.click(int(x), int(y))

    def get_offset_loc(self, x, y, offset_x=0, offset_y=0):
        x = round(x + self.pixels_per[0] * offset_x)
        y = round(y + self.pixels_per[1] * offset_y)
        return x, y

    def get_current_loc(self, x, y):
        x = round(self.pixels_per[0] * x)
        y = round(self.pixels_per[1] * y)
        return x, y

    def slide_screen_up(self, distance=100):
        start_x = self.pixels[0] // 2
        start_y = self.pixels[1] // 2 + distance
        end_x = start_x
        end_y = self.pixels[1] // 2 - distance
        if CONFIG.my_action_log:
            print(f"[slide_screen_up]:({start_x},{start_y}) -> ({end_x},{end_y})")
        action.slide(start_x, start_y, end_x, end_y)

    def slide_screen_left(self):
        start_x = self.pixels[0] // 2 + 100
        start_y = self.pixels[1] // 2
        end_x = self.pixels[0] // 2 - 100
        end_y = start_y
        if CONFIG.my_action_log:
            print(f"[slide_screen_left]:({start_x},{start_y}) -> ({end_x},{end_y})")
        action.slide(start_x, start_y, end_x, end_y)

    def go_back(self):
        action.Key.back()

    def find_time(self, leftup, rightdown):
        bitmap = screen.capture(leftup[0], leftup[1], rightdown[0], rightdown[1])
        res = Ocr.mlkitocr_v2(bitmap=bitmap)
        if res is None:
            if CONFIG.my_action_log:
                print("[find_time]文字识别失败")
            return None
        _time = None
        for r in res:
            text = r.text
            match = re.search("[0-9]+", text)
            if match:
                _time = int(match.group())
            if text.find("分") != -1:
                _time = _time * 60
            break
        return _time

    def has_text(self, text):
        res = Ocr.mlkitocr_v2()
        if res is None:
            if CONFIG.my_action_log:
                print("[has_text]文字识别失败")
            return False
        else:
            for r in res:
                if CONFIG.my_action_log:
                    print(f"[has_text]: {r.text}")
                if text == r.text:
                    return True
        return False

    def restart_app(self):
        action.Key.recents()
        time.sleep(2)
        self.slide_screen_up()
        time.sleep(2)
        action.Key.home()
